package user_service

import (
	"gin-gorm-project/modules/user"
	"github.com/gin-gonic/gin"
	"net/http"
	"strconv"
	"sync"
	"time"
)

type UserService struct {
}

func (userService *UserService) QueryByPage(context *gin.Context) {
	buildUser := user.User{}
	buildUser.UserName = context.PostForm("userName")
	buildUser.Password = context.PostForm("password")
	buildUser.Jurisdiction = context.PostForm("jurisdiction")
	buildUser.Information = context.PostForm("information")
	pageNumber, err := strconv.Atoi(context.PostForm("pageNumber"))
	if err != nil {
		context.JSON(http.StatusInternalServerError, gin.H{
			"message": "查询出现错误，请确认翻页数据是否正确",
		})
		return
	}
	pageSize, err := strconv.Atoi(context.PostForm("pageSize"))
	if err != nil {
		context.JSON(http.StatusInternalServerError, gin.H{
			"message": "查询出现错误，请确认翻页数据是否正确",
		})
		return
	}
	response := buildUser.QueryByPage(pageNumber, pageSize)
	context.JSON(http.StatusOK, gin.H{
		"data": response,
	})
}

func (userService *UserService) Save(r *gin.Context) {
	buildUser := user.User{}
	buildUser.UserName = r.PostForm("userName")
	buildUser.Password = r.PostForm("password")
	buildUser.Jurisdiction = r.PostForm("jurisdiction")
	buildUser.Information = r.PostForm("information")
	//fmt.Println(buildUser)
	buildUser.Save()
	r.JSON(http.StatusOK, gin.H{
		"message": "保存成功",
		"id":      buildUser.Id,
	})
}

func (userService *UserService) QueryAll(context *gin.Context) {
	u := user.User{}
	var response = u.QueryAll()
	context.JSON(http.StatusOK, gin.H{
		"data": response,
	})
}

func (userService *UserService) BuildDemoUser(context *gin.Context) {

	var myWaitGroup sync.WaitGroup
	var newIds = []int{}
	buildFunction := func(user user.User) {
		user.Save()
		newId := user.Id
		newIds = append(newIds, newId)
		myWaitGroup.Done()
	}
	beginTime := time.Now()
	for i := 0; i < 100; i++ {
		myWaitGroup.Add(1)
		var a = strconv.Itoa(i)
		var inputUser = user.User{
			UserName:     "demoUser" + a,
			Password:     "demoPassword" + a,
			Jurisdiction: "demoJurisdiction" + a,
			Information:  "demoInformation" + a,
		}
		go buildFunction(inputUser)
	}
	myWaitGroup.Wait()
	endTime := time.Now()

	var maxId int
	for _, id := range newIds {
		if maxId < id {
			maxId = id
		}
	}

	context.JSON(http.StatusOK, gin.H{
		"message":    "测试数据生成完成",
		"time":       endTime.Sub(beginTime).Seconds(),
		"buildMaxId": maxId,
	})

}
